package models

import (
	"t11Lib/t11Errors"
	"t11Lib/t11Model"
)

//用户跟门锁的绑定关系
type UserDevice struct {
	t11Model.BaseMdl
	DevId    string
	UserId   string
	MasterId string
	BindType string
}

type userDeviceDao struct{}

var UserDeviceDao userDeviceDao

func (self userDeviceDao) GetTokensByDeviceId(conn *t11Model.DbConn, devId string) ([]*JwtToken, t11Errors.T11Error) {
	var devs []*UserDevice
	_, e := conn.QueryTable(&UserDevice{}).Filter("DevId", devId).All(&devs)
	if e != nil {
		return nil, t11Errors.Wrap(e)
	}
	var ret []*JwtToken
	for _, item := range devs {
		ret = append(ret, ParseJwtToken(item.UserId))
	}
	return ret, nil
}

func (self userDeviceDao) GetUserDeviceByUser(conn *t11Model.DbConn, token *JwtToken) (*UserDevice, t11Errors.T11Error) {

	d := &UserDevice{}
	d.UserId = token.ToId()
	e := conn.Read(d, "UserId")
	return d, t11Errors.Wrap(e)
}

func (self userDeviceDao) Get(conn *t11Model.DbConn, devId string, client *JwtToken) (*UserDevice, t11Errors.T11Error) {
	d := &UserDevice{}
	d.DevId = devId
	d.UserId = client.ToId()
	e := conn.Read(d, "DevId", "UserId")
	return d, t11Errors.Wrap(e)
}

func (self userDeviceDao) Delete(conn *t11Model.DbConn, devId string, token *JwtToken) t11Errors.T11Error {
	d := &UserDevice{}
	d.DevId = devId
	d.UserId = token.ToId()
	_, e := conn.Delete(d, "DevId", "UserId")
	return t11Errors.Wrap(e)
}

func (self userDeviceDao) DeleteByDevId(conn *t11Model.DbConn, devId []string) t11Errors.T11Error {
	_, e := conn.QueryTable(&UserDevice{}).Filter("DevId__in", devId).Delete()
	return t11Errors.Wrap(e)
}

func (self userDeviceDao) Create(conn *t11Model.DbConn, devId, userId, adminUserId, bindType string) t11Errors.T11Error {
	item := &UserDevice{}
	item.Id = devId + userId
	item.UserId = userId
	item.DevId = devId
	item.MasterId = adminUserId
	item.BindType = bindType
	_, e := conn.Insert(item)
	return t11Errors.Wrap(e)
}

func (self userDeviceDao) GetUsersByDeviceId(conn *t11Model.DbConn, devId string) ([]*UserDevice, t11Errors.T11Error) {

	var devs []*UserDevice
	_, e := conn.QueryTable(&UserDevice{}).Filter("DevId", devId).All(&devs)
	if e != nil {
		return nil, t11Errors.Wrap(e)
	}

	return devs, nil
}
